package com.jplus.plugin.rpc.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.plugin.rpc.codec.LineDecoder;
import com.jplus.plugin.rpc.process.JsonRpcProcess;
import com.jplus.plugin.rpc.process.NIOProcess;

public class NIOClient extends NIO {
	final Logger log = LoggerFactory.getLogger(NIOClient.class);

	public static void main(String[] args) throws IOException, InterruptedException {
		System.out.println("NIOClient");
		JsonRpcProcess jsonp = new JsonRpcProcess(NIORole.CLIENT, new LineDecoder());
		new NIOClient("127.0.0.1", 8088, jsonp).start();

		int i = 0;
		while (++i > 0) {
			byte[] b = ("{\"message\":\"Success!\",\"index\":\"" + i + "\"}").getBytes();
			jsonp.addMsg(ByteBuffer.wrap(b));
			Thread.sleep(1000);
		}

	}

	public NIOClient(String host, int port, NIOProcess process) throws IOException {
		super.process = process;
		super.threadPool = Executors.newFixedThreadPool(5);
		//
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		super.selector = Selector.open();
		sc.register(selector, SelectionKey.OP_CONNECT);
		sc.connect(new InetSocketAddress(host, port));
		System.out.println("OK");
	}

}